package com.cloudfun.campusshare.configuration.interceptors;

import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;

/**
 * @author wangxiyuan
 * @description
 * @createDate 2021/5/19 9:21
 **/
@Slf4j
@Aspect
@Component
public class ControllerLogAcpect {
    private ThreadLocal<Long> startTime = new ThreadLocal<>();
    private ThreadLocal<HttpServletRequest> localRequest = new ThreadLocal<>();
    private ThreadLocal<JoinPoint> localJoinPoint = new ThreadLocal<>();

    /**
     * 定义切入点，切入点为com.example.aop下的所有函数
     */
    @Pointcut("execution(* com.cloudfun.campusshare.controller..*.*(..)))")
    public void webLog() {
    }

    /**
     * 前置通知：在连接点之前执行的通知
     *
     * @param joinPoint
     * @throws Throwable
     */
    @Before("webLog()")
    public void doBefore(JoinPoint joinPoint) {
        log.warn("------------------------------------------------ controller start ----------------------------------------------------------");
        startTime.set(System.currentTimeMillis());
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        localRequest.set(request);
        localJoinPoint.set(joinPoint);
    }

    @AfterReturning(returning = "response", pointcut = "webLog()")
    public void doAfterReturning(Object response)  {
        HttpServletRequest request = localRequest.get();
        JoinPoint joinPoint = localJoinPoint.get();
        log.warn("URL:{}?{} [{}]",request.getRequestURL(),request.getQueryString(), request.getMethod());
        log.warn("IP:{}",request.getRemoteAddr());
        log.warn("CLASS_METHOD:{}",joinPoint.getSignature().getDeclaringTypeName()+"."+joinPoint.getSignature().getName());
        log.warn("ARGS:{}", Arrays.toString(joinPoint.getArgs()));
//        log.warn("RESPONSE:{}", response);
        log.warn("SPEND TIME:{}", (System.currentTimeMillis() - startTime.get()));
        log.warn("------------------------------------------------ controller end ----------------------------------------------------------\n");
    }
}
